<template>
  <view>
    <view class="gg-ls-tabbox-wrap" v-if="tabsShow">
      <block v-for="(item, index) in localTabs" :key="index">
        <view class="gg-ls-tabbox-item" :class="tabCurr == index ? 'on' : ''" :data-current="index" @tap="changeTab">{{ item.nav }}</view>
        <!-- <view style="display:flex;">
          <text>{{ item.nav }}</text>
          <view class="gg-ls-tabbox-sort-wrap shop-nav-img" v-if="item.orderby">
            <view class="shop-price-up">
              <image src="/static/mall_img/cart_value_up_yes.png" v-if=" item.ordersort=='asc' "></image>
              <image src="/static/mall_img/cart_value_up.png" v-else></image>
            </view>
            <view class="shop-price-down">
              <image src="/static/mall_img/cart_value_down_yes.png" v-if=" item.ordersort=='desc' "></image>
              <image src="/static/mall_img/cart_value_down.png" v-else></image>
            </view>
          </view>
        </view>
    </view> -->
      </block>
    </view>

    <swiper :current="tabCurr" class="swiper-box" duration="300" :style="settHeight1" @animationfinish="changeSwipwe">
      <swiper-item v-for="(item, index) in localTabs" :key="index">
        <!-- #ifndef APP-PLUS||H5 -->
        <mescroll-uni :index="index" top="80" :up="settUpOpt" :down="settDownOpt" @down="refresh" @init="mescrollInit">
          <!-- #endif -->
          <scroll-view :style="settHeight1" style="height: 100%;width: 100%;" scroll-with-animation @scroll="onviewscroll" scroll-y="true"
            :refresher-triggered="triggered" :refresher-threshold="100" refresher-background="#eee" @refresherrefresh="onLsRefresh"
            @refresherrestore="onLsRestore" @refresherabort="onLsAbort" @scrolltoupper="onLsScrolltoUpper" @scrolltolower="onLsScrolltoLower"
            lower-threshold="200">
            <!-- <scroll-view :style="settHeight2" @scroll="onviewscroll"  scroll-y="true"> -->

            <!-- #ifdef APP-PLUS||H5 -->
            <view style="width: 100%;" :class=" tabsShow&&'gg-ls-tabsShow' "></view>
            <!-- #endif -->

            <view v-if="localTabs[index].data.length > 0" :class=" listsClass">
              <view v-for="(dataRow,dataIndex) in localTabs[index].data " :key="dataIndex">
                <slot name="default" v-bind:rows="dataRow" v-bind:index="dataIndex" v-bind:tabIndex="index"></slot>
              </view>
            </view>
            <view v-if="localTabs[index].has_more != 4" class="gg-ls-ft" @tap="onLsScrolltoLower"
              :class=" (localTabs[index].has_more == 3  && localTabs[index].data.length<1)&& 'gg-ls-end-nodata' ">
              <view v-if="localTabs[index].has_more === 1" class="gg-ls-loading">
                <view style="font-size: 16px;height:16px;"></view>
              </view>
              <view v-if="localTabs[index].has_more == 3 && localTabs[index].data.length<1 " class="gg-ls-nodata">
                <image src="/static/common/zwsj.png"></image>
              </view>
              <text>{{ localTabs[index].has_more == 3 ? localLoad.nodata : loadingText[localTabs[index].has_more] }}</text>
            </view>
          </scroll-view>
          <!-- #ifndef APP-PLUS||H5 -->
        </mescroll-uni>
        <!-- #endif -->
      </swiper-item>
    </swiper>

    <!-- <view class="swiper-box" :style="style">
      <view v-for="(item, index) in localTabs" :key="index"></view>
    </view> -->

  </view>
</template>
<script>
export default {
  name: "GgListsSwiper",
  props: {
    // tabs 配置
    tabsConfig: {
      type: [Array, Object],
      default: []
    },
    // 是否显示tabs
    tabsShow: {
      type: Boolean,
      default: true
    },
    currentTab: {
      type: [Number, String],
      default: 0
    },
    loadArr: {
      type: Object,
      default() {
        return {}
      }
    },
    listsClass: {
      type: String,
      default: ''
    },
  },
  watch: {
    currentTab(newVal) {
      this.tabCurr = parseInt(newVal);
      this._doRef();
    }
  },
  data() {
    return {
      localTabs: [],
      tabCurr: 0,
      localLoad: {
        'nodata': '暂无数据'
      },
      settHeight1: 'auto', // 窗口高度
      settHeight2: 'auto',
      settPxr: 0, //比例
      triggered: false,
      loadingText: ['点击加载更多', '正在加载...', '没有更多了', '暂无数据', ''],
      //组件参数
      settUpOpt: {
        use: false
      },
      settDownOpt: {
        use: true,
        auto: false
      },
      scrollTop: 0,
      old: {
        scrollTop: 0
      }
    };
  },
  created() {
    this.localLoad = this.loadArr || this.localLoad;
    this.tabCurr = parseInt(this.currentTab);
    this.localTabs = this.tabsConfig;
    //   this.localTabs.forEach((itemTabs, itemIndex) => {
    for (let i in this.localTabs) {
      let itemTabs = this.localTabs[i];

      this.localTabs[i] = Object.assign({}, {
        has_more: 1,
        ordersort: 'desc',// 排序
        orderby: '',// 排序字段名
        pagesize: 10,
        page: 1,
        status: true,
        data: []
      }, this.localTabs[i]);
    }
    this._dealHeight();
    this._doRef();
  },
  mounted() {
    // console.log(this.listsClass)
    this._doRef();
  },
  methods: {
    _doRef() {
      if (this.localTabs[this.tabCurr].status) {
        this.refresh('', true);
      }
    },
    _dealHeight() {
      // 获取系统页面信息
      uni.getSystemInfo({
        success: (res) => {
          var clientHeight = res.windowHeight,
            clientWidth = res.windowWidth,
            rpxR = 750 / clientWidth; // 比例
          var calc = clientHeight * rpxR;
          this.settPxr = 1 / rpxR;

          // this.$nextTick(function () {
          // let winHeight = clientHeight - 85 + 'px';
          //   this.winHeight = calc;
          let winHeight = clientHeight + 'px';
          this.settHeight1 = 'height:' + winHeight;
          this.settHeight2 = 'height:' + (winHeight - 40) + 'px';

          // });
        }
      });

      // #ifdef APP-PLUS||H5
      // this.winHeight = uni.upx2px(calc - 70) + 'px';
      // // #endif
      // // #ifndef APP-PLUS||H5
      // this.winHeight = uni.upx2px(calc - 170) + 'px';
      // // #endif
      // this.scrollTop = this.old.scrollTop;
      // this.$nextTick(function () {
      //   console.log('aaaaaaa');
      //   this.scrollTop = 100;
      // });

    },
    /*** 点击tab切换*/
    changeTab(e) {
      let clickIndex = parseInt(e.currentTarget.dataset.current);
      if (this.tabCurr === clickIndex) {
        return false;
      } else {
        this.tabCurr = clickIndex;
        // console.log(clickIndex);
        let localItem = this.localTabs[this.tabCurr] || {};
        if (localItem.orderby) {
          this.localTabs[this.tabCurr].ordersort = localItem.ordersort == 'desc' ? 'asc' : 'desc';
        }
        if (localItem.status) {
          this.refresh('', true);
        }
      }
    },
    /*** 滑动切换tab*/
    changeSwipwe(e) {
      this.tabCurr = parseInt(e.detail.current);
      if (this.localTabs[this.tabCurr].status) {
        this.refresh('', true);
      }
    },
    // 下拉刷新
    onLsRefresh(e) {
      // console.log("onLsRefresh", e);
      this.localTabs[this.tabCurr].has_more = 1;
      uni.stopPullDownRefresh();
      // onPullDownRefresh
      if (this.scrollTop > 20) {
        return;
      }
      this.refresh();
      this.triggered = true;
      this.$nextTick(() => {
        this.triggered = false;
      });
      if (this._freshing) return;
      this._freshing = true;
      setTimeout(() => {
        this.localTabs[this.tabCurr].has_more = 3;
        this.triggered = false;
        this._freshing = false;
      }, 1500)
    },
    //刷新
    refresh: async function (mescroll, first) {
      // uni.showNavigationBarLoading();
      if (first == true) {
        this.localTabs[this.tabCurr].has_more = 1;
      } else {
        this.localTabs[this.tabCurr].has_more = 4;
      }
      this.localTabs[this.tabCurr].page = 1;
      this.localTabs[this.tabCurr].data = [];
      this.localTabs[this.tabCurr].status = false;
      this.triggered = 'restore'; // 需要重置
      this.triggered = false;
      // console.log('无法调用');
      // await this.$emit('onAjaxData', this.tabCurr, this.localTabs[this.tabCurr]);
      await this.getAjaxData(this.tabCurr, this.localTabs[this.tabCurr]);
      // console.log('无法调用222');
      uni.stopPullDownRefresh();
      uni.hideNavigationBarLoading()
      if (mescroll) mescroll.endDownScroll();
    },
    onLsRestore() {
      this.triggered = 'restore'; // 需要重置
      // console.log("onRestore");
    },
    onLsAbort() {
      // console.log("onAbort");
      if (this.triggered) {
        this.$nextTick(() => {
          this.triggered = false;
        });
      }
      setTimeout(() => {
        uni.stopPullDownRefresh();
      }, 1500);
    },
    getAjaxData(tabCurrIndex, tabCurrItem) {
      let currItem = this.localTabs[this.tabCurr];
      if (this.localTabs[this.tabCurr]['apiFunc']) {
        //接口方法请求
        console.warn('执行方法', this.localTabs[this.tabCurr]['apiFunc']);

        // if (successRes.data.length == 0) {
        //   this.$message.show('无更多商铺~');
        //   return;
        // } else {
        //   this.$message.show('加载中...');
        // }
        return new Promise((res) => {
          // console.log('--');
          let clock = setTimeout(() => {
            setTimeout(() => {
              currItem.has_more = 3;
              uni.hideToast();
              res();
            }, 200);
          }, 1000);
          let orderParam = {};
          if (this.localTabs[this.tabCurr].orderby) {
            orderParam = {
              orderby: this.localTabs[this.tabCurr].orderby,
              ordersort: this.localTabs[this.tabCurr].ordersort,
            };
          }
          this.localTabs[this.tabCurr]['apiFunc']({
            ...this.localTabs[this.tabCurr].param,
            ...orderParam,
            page: this.localTabs[this.tabCurr].page,
          }).then((successRes) => {
            for (let i in successRes.data) {
              this.localTabs[this.tabCurr].data.push(successRes.data[i]);
            }
            // console.log('--', this.localTabs[this.tabCurr]);

            //是否有下一页判断
            if (this.localTabs[this.tabCurr].page >= successRes.pagemax) {
              this.localTabs[this.tabCurr].has_more = 2;
            } else {
              this.localTabs[this.tabCurr].has_more = 0;
              this.localTabs[this.tabCurr].page++; // 页数+1
            }
            if (successRes.total == 0) this.localTabs[this.tabCurr].has_more = 3;

            setTimeout(() => {
              this.$forceUpdate();
              uni.hideToast();
              uni.stopPullDownRefresh();
            }, 1000);
            clearTimeout(clock);
            res();
            // this.dealDataList(successRes.data, this.tabCurr, page);
          });
        });
      }
    },
    // mescroll组件初始化的回调,可获取到mescroll对象
    mescrollInit(mescroll) {
      this.mescroll = mescroll;
    },
    onviewscroll(e) {
      // #ifndef APP-PLUS
      // this.mescroll && this.mescroll.onPageScroll({ scrollTop: e.detail.scrollTop });
      // #endif
      // #ifdef APP-PLUS
      const pages = getCurrentPages();
      const page = pages[pages.length - 1];
      const currentWebview = page.$getAppWebview();

      switch (uni.getSystemInfoSync().platform) {
        case 'android':
          // if (e.detail.scrollTop > 20) currentWebview.setPullToRefresh({
          if (e.detail.scrollTop > 50) currentWebview.setPullToRefresh({
            support: false
          });
          else {
            currentWebview.setPullToRefresh({
              support: true,
              style: 'circle',
              offset: '0'
            });
          }
          break;
        case 'ios':
          this.scrollTop = e.detail.scrollTop;
          if (e.detail.scrollTop > 60) {
            currentWebview.endPullToRefresh();
          }
          break;
        default:
          break;
      }
      // #endif
    },

    onLsScrolltoUpper(e) {
      // console.log("onLsScrolltoUpper", e);
    },
    /**
     * 页面上拉触底事件的处理函数
     */
    onLsScrolltoLower: async function () {
      if (this.localTabs[this.tabCurr].has_more != 0) {
        uni.hideToast();
        return;
      }
      // 显示加载图标
      uni.showToast({
        title: '加载中...',
        icon: 'loading',
        duration: 100000000
      });
      this.localTabs[this.tabCurr].has_more = 1;
      // await this.$emit('onAjaxData', this.tabCurr);
      await this.$emit('onAjaxData', this.tabCurr, this.localTabs[this.tabCurr]);
    },

    onPageScroll: function (scrollNum) {
    }
  }
}
</script>
<style>
.gg-ls-end-nodata {
  margin-top: 80px;
}
.gg-ls-tabsShow {
  margin-top: 40px;
}
.gg-ls-tabbox-wrap {
  background: #f6f6f6;
  box-sizing: border-box;
  width: 100%;
  height: 70rpx;
  padding-top: 10rpx;
  display: flex;
  display: -webkit-box;
  display: -webkit-flex;
  flex-direction: row;
  font-size: 28rpx;
  text-align: center;
  /* box-shadow: 0 1px 5px 0 #eee; */ /* border-bottom: 2rpx solid #eee; */

  position: fixed;
  top: 0;
  left: 0;
  /* #ifdef H5 */
  margin-top: 44px;
  /* #endif */
  z-index: 665;
}
.gg-ls-tabbox-item {
  flex: 1;
  -webkit-flex: 1;
  line-height: 50rpx;
  padding: 5rpx;
  padding-bottom: 0;
  font-size: 30rpx;
  margin: 0 10rpx;
}
.gg-ls-tabbox-item.on {
  color: #19c7b7;
  border-bottom: 6rpx solid #19c7b7;
}
.gg-ls-tabbox-sort-wrap {
  position: absolute;
  top: 12px;
}
/* 无更多数据 */
.gg-ls-ft {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  text-align: center;
  color: grey;
  padding: 20rpx 0;
  font-size: 28rpx;
  width: 100%;
  min-height: 90rpx;
  margin-bottom: 20rpx;
}
.gg-ls-ft text {
  color: grey;
}

/* 無內容樣式 */
.gg-ls-nodata {
  width: 100%;
  display: flex;
  display: -webkit-box;
  display: -webkit-flex;
  flex-direction: column;
  align-items: center;
  -webkit-align-items: center;
  padding-top: 100rpx;
}
.gg-ls-nodata image {
  width: 360rpx;
  height: 290rpx;
  margin-bottom: 80rpx;
}
.gg-ls-nodata text {
  font-size: 32rpx;
  color: rgb(111, 111, 111);
}

.gg-ls-loading {
  display: inline-block;
  width: 16px;
  height: 16px;
  border-radius: 50%;
  border: 2px solid gray;
  border-bottom-color: transparent;
  vertical-align: middle;
  margin-right: 5px;
  animation: Loading 0.6s linear infinite;
  -webkit-animation: Loading 0.6s linear infinite;
}
</style>